//
//  Button.swift
//  SwiftHub
//
//  Created by Khoren Markosyan on 1/4/17.
//  Copyright © 2017 Khoren Markosyan. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
import RxTheme

extension ThemeProxy where Base: UIButton {
    
    func backgroundImage(from newValue: ThemeAttribute<UIColor?>, for state: UIControl.State) -> Void {
        let img = UIImage(color: newValue.value ?? .clear, size: CGSize(width: 1, height: 1))
        base.setBackgroundImage(img, for: state)
        let disposable = newValue.stream
            .take(until: base.rx.deallocating)
            .observe(on: MainScheduler.instance)
            .map {
                UIImage(color: $0 ?? .clear, size: CGSize(width: 1, height: 1))
            }
            .bind(to: base.rx.backgroundImage(for: state))
        hold(disposable, for: "backgroundImage.forState.\(state.rawValue)")
    }
}

public class Button: UIButton {

    override init(frame: CGRect) {
        super.init(frame: frame)
        makeUI()
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        makeUI()
    }

    func makeUI() {
        theme.titleColor(from: themed { $0.text }, for: .normal)
        theme.backgroundImage(from: themed { $0.secondary }, for: .normal)
        theme.backgroundImage(from: themed { $0.secondary.withAlphaComponent(0.9) }, for: .selected)
        theme.backgroundImage(from: themed { $0.secondary.withAlphaComponent(0.6) }, for: .disabled)
        
        layer.masksToBounds = true
        titleLabel?.lineBreakMode = .byWordWrapping
        layerCornerRadius = Configs.BaseDimensions.cornerRadius
//        font = font?.withSize(14)

        snp.makeConstraints { (make) in
            make.height.equalTo(Configs.BaseDimensions.buttonHeight)
        }

        updateUI()
    }

    func updateUI() {
        setNeedsDisplay()
    }
}
